import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Layout, Menu, Upload, Button, Image, Typography, Card, Alert,
  Descriptions, Row, Col, Statistic, Timeline, message, Tabs, Modal,
  Badge, Form, Input, Select, Empty, Space, Divider, Avatar, Tag,
  Table, Progress, Switch, Drawer, Tooltip, Collapse,
  ConfigProvider, BackTop, Dropdown, Breadcrumb,
  Radio, Checkbox, Slider, Result, Spin, Steps, InputNumber, theme as antdTheme,
  List, Segmented, FloatButton, theme
} from 'antd';
import {
  DashboardOutlined, HistoryOutlined, SettingOutlined,
  BarChartOutlined, SafetyOutlined, WarningOutlined, UserOutlined,
  ClockCircleOutlined, VideoCameraOutlined, BellOutlined, CheckCircleOutlined,
  TeamOutlined, SafetyCertificateOutlined, AlertOutlined, PlusOutlined,
  ReloadOutlined, FilterOutlined, BulbOutlined, PoweroffOutlined,
  ExperimentOutlined, RobotOutlined,
  CrownOutlined,
  ThunderboltOutlined, BookOutlined, SolutionOutlined, ReadOutlined,
  MenuUnfoldOutlined, MenuFoldOutlined, PictureOutlined, SendOutlined,
  InfoCircleOutlined, ClearOutlined, FundProjectionScreenOutlined,
  CustomerServiceOutlined, CodeSandboxOutlined, TrademarkCircleOutlined,
  AppstoreAddOutlined, RadarChartOutlined
} from '@ant-design/icons';
import { Chart } from 'react-google-charts';
import moment from 'moment';
import axios from 'axios';
import io from 'socket.io-client';
import './App.css';

const { Header, Content, Sider, Footer } = Layout;
const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;
const { Panel } = Collapse;
// const { /* Step */ } = Steps; // 移除此行，解决警告
const { Dragger } = Upload;
const { useToken } = theme; // Ant Design 5.x 推荐的获取主题 token 方式

// 系统常量
const BACKEND_URL = 'http://43.139.21.83:8000';

const campusLocations = [
  '教学楼A栋', '教学楼B栋', '图书馆', '食堂', '体育馆', '宿舍区', '校门口', '操场',
  '行政楼', '实验楼', '艺术楼', '停车场', '篮球场', '网球场', '游泳馆', '校医院'
];

// eslint-disable-next-line no-unused-vars
const behaviorTypes = [ // 保留：尽管未直接使用，但其数据结构在后端定义和前端渲染（例如renderPersonDetails）中仍有逻辑依赖，如颜色和标签匹配
  { label: '正常行为', value: 'normal', color: 'green' },
  { label: '危险行为', value: 'danger', color: 'red' },
  { label: '可疑行为', value: 'suspicious', color: 'orange' },
  { label: '跌倒', value: 'fall', color: 'volcano' },
  { label: '奔跑', value: 'run', color: 'gold' },
  { label: '聚集', value: 'crowd', color: 'purple' },
  { label: '站立', value: 'stand', color: 'blue' },
  { label: '行走', value: 'walk', color: 'cyan' },
  { label: '弯腰', value: 'bend', color: 'magenta' }
];

const deviceStatusTypes = [
  { label: '在线', value: 'online', color: 'green' },
  { label: '离线', value: 'offline', color: 'gray' },
  { label: '故障', value: 'error', color: 'red' },
  { label: '维护中', value: 'maintenance', color: 'orange' }
];

const deviceTypes = [
  { label: '摄像头', value: 'camera' },
  { label: '门禁', value: 'access_control' },
  { label: '烟雾报警器', value: 'smoke_detector' },
  { label: '其他', value: 'other' },
];

const DEFAULT_SYSTEM_SETTINGS = {
  sensitivity: 'medium',
  notification: 'all',
  retention: '30',
  interval: '10',
  theme: 'light', // 默认亮色模式
  active_theme: 'standard-light', // 默认亮色皮肤
  model_version: 'yolov8n-pose',
  confidence_threshold: 50,
  notification_methods: ['system'],
  sound_reminders: true,
  ai_interpret_results: true,
  ai_proactive_alerts: true,
  app_builder_app_id: '8ecbe3f6-5fdf-45ea-b23c-387909c66d70'
};

// 辅助函数
const generateUniqueId = () => `id-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

function App() {
  const videoRef = useRef(null);
  const aiChatMessagesEndRef = useRef(null);
  // ErnieChatConversationId在前端生成并传递给后端，这样可以实现会话保持
  const [ernieChatConversationId] = useState(generateUniqueId());
  const { token } = useToken(); // 获取 Ant Design 默认主题 token

  // 状态管理
  const [imageUrl, setImageUrl] = useState(null);
  const [originalImageForAnalysis, setOriginalImageForAnalysis] = useState(null);
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [history, setHistory] = useState([]);
  const [systemLogs, setSystemLogs] = useState([]);
  const [activeTab, setActiveTab] = useState('1');
  const [collapsed, setCollapsed] = useState(false);

  const [stats, setStats] = useState({
    totalDetections: 0, alerts: 0, safePersons: 0, devices: 0, onlineDevices: 0,
    behaviorStats: [], locationStats: [], timeTrend: []
  });

  const [emergencyModalVisible, setEmergencyModalVisible] = useState(false);
  const [checkinModalVisible, setCheckinModalVisible] = useState(false);
  const [liveModalVisible, setLiveModalVisible] = useState(false);
  const [addDeviceModalVisible, setAddDeviceModalVisible] = useState(false);
  const [alertDrawerVisible, setAlertDrawerVisible] = useState(false);

  const [emergencyForm] = Form.useForm();
  const [checkinForm] = Form.useForm();
  const [settingsForm] = Form.useForm();
  const [addDeviceForm] = Form.useForm();
  const [modelTrainForm] = Form.useForm();
  const [aiChatForm] = Form.useForm();

  const [notifications] = useState([
    { id: 1, title: '系统更新', time: '10分钟前', type: 'info', read: false },
    { id: 2, title: '摄像头离线', time: '30分钟前', type: 'warning', read: false },
    { id: 3, title: '新告警', time: '1小时前', type: 'error', read: false }
  ]);

  const [devices, setDevices] = useState([]); // 从后端加载
  const [alerts, setAlerts] = useState([
    {
      id: 'alert-001',
      title: '检测到可疑行为',
      level: { label: '中', value: 'medium', color: 'orange' },
      location: '图书馆',
      time: '2023-11-15 09:45:23',
      status: '未处理',
      description: '检测到一名人员在图书馆区域徘徊超过30分钟'
    },
    {
      id: 'alert-002',
      title: '设备离线',
      level: { label: '低', value: 'low', color: 'blue' },
      location: '体育馆',
      time: '2023-11-14 16:30:45',
      status: '处理中',
      description: '体育馆摄像头已离线超过24小时'
    }
  ]);
  const [persons, setPersons] = useState([]); // 从后端加载

  const [selectedCamera, setSelectedCamera] = useState(null);
  const [currentStreamUrl, setCurrentStreamUrl] = useState(null);
  const [darkModeActive, setDarkModeActive] = useState(false);
  const [selectedAlert, setSelectedAlert] = useState(null);
  const [selectedPerson, setSelectedPerson] = useState(null);
  const [selectedDevice, setSelectedDevice] = useState(null);
  const [currentTime, setCurrentTime] = useState(moment());
  const [dashboardView, setDashboardView] = useState('cards'); // 'cards' or 'charts'

  const [modelTrainProgress, setModelTrainProgress] = useState(0);
  const [modelTrainStatus, setModelTrainStatus] = useState('wait');
  const [modelTrainJobDetails, setModelTrainJobDetails] = useState(null);
  const [modelTrainQueue, setModelTrainQueue] = useState([]);

  const [qianfanCheckLoading, setQianfanCheckLoading] = useState(false);
  const [qianfanCheckResult, setQianfanCheckResult] = useState(null);

  const [aiInterpretation, setAiInterpretation] = useState(null);
  const [aiInterpretationLoading, setAiInterpretationLoading] = useState(false);

  const [aiProactiveInsight, setAiProactiveInsight] = useState(null);
  const [aiProactiveInsightLoading, setAiProactiveInsightLoading] = useState(false);

  const [aiAlertRecommendations, setAiAlertRecommendations] = useState(null);
  const [aiAlertRecommendationsLoading, setAiAlertRecommendationsLoading] = useState(false);

  const [aiChatMessages, setAiChatMessages] = useState([
    { id: '1', role: 'assistant', content: '您好！我是智守AI助手，有什么校园安全相关的问题可以问我？', time: moment().format('HH:mm') }
  ]);

  const [aiChatLoading, setAiChatLoading] = useState(false);

  const [imageQuestion, setImageQuestion] = useState('请描述这张图片的内容。');
  const [imageInterpretResult, setImageInterpretResult] = useState(null);
  const [imageInterpretLoading, setImageInterpretLoading] = useState(false);
  const [imageUploadFile, setImageUploadFile] = useState(null);

  const [systemStatus, setSystemStatus] = useState({
    cpu: 0, memory: 0, storage: 0, network: 0,
    appbuilder_client_initialized: false, qianfan_token_available: false
  });

  // 系统设置状态
  const [systemSettings, setSystemSettings] = useState(DEFAULT_SYSTEM_SETTINGS);

  // 应用主题
  const applyTheme = useCallback((settings) => {
    const isDarkMode = settings.theme === 'dark';
    setDarkModeActive(isDarkMode);

    // 更新文档主题类
    document.documentElement.dataset.antdTheme = isDarkMode ? 'dark' : 'light';
    document.documentElement.classList.forEach(cls => {
      if (cls.startsWith('theme-')) document.documentElement.classList.remove(cls);
    });
    document.documentElement.classList.add(`theme-${settings.active_theme || 'standard-light'}`);
  }, []);

  // 加载设置
  const loadSettings = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/settings`);
      const loadedSettings = response.data.settings;
      setSystemSettings(loadedSettings);
      settingsForm.setFieldsValue(loadedSettings);
      applyTheme(loadedSettings);
      message.success('系统设置加载成功！');
    } catch (error) {
      console.error('加载系统设置失败:', error);
      message.error('加载系统设置失败: ' + (error.response?.data?.error || error.message));
      applyTheme(DEFAULT_SYSTEM_SETTINGS); // 失败时应用默认设置
    }
  }, [settingsForm, applyTheme]);

  // 保存设置
  const handleSaveSettings = async (values) => {
    try {
      setLoading(true);
      const response = await axios.post(`${BACKEND_URL}/api/settings`, values);
      setSystemSettings(values); // 更新前端状态
      applyTheme(values); // 立即应用主题
      message.success(response.data.message);
    } catch (error) {
      console.error('保存系统设置失败:', error);
      message.error('保存系统设置失败: ' + (error.response?.data?.error || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 加载历史记录
  const loadHistory = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/history`);
      setHistory(response.data);
      message.success('历史记录加载成功！');
    } catch (error) {
      console.error('加载历史记录失败:', error);
      message.error('加载历史记录失败: ' + (error.response?.data?.error || error.message));
    }
  }, []);

  // 加载统计数据
  const loadStats = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/stats`);
      setStats(response.data);
      message.success('数据统计加载成功！');
    } catch (error) {
      console.error('加载统计数据失败:', error);
      message.error('加载统计数据失败: ' + (error.response?.data?.error || error.message));
    }
  }, []);

  // 加载设备列表
  const loadDevices = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/devices_list`);
      setDevices(response.data);
      message.success('设备列表加载成功！');
    } catch (error) {
      console.error('加载设备列表失败:', error);
      message.error('加载设备列表失败: ' + (error.response?.data?.error || error.message));
    }
  }, []);

  // 加载人员列表
  const loadPersons = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/persons_list`);
      setPersons(response.data);
      message.success('人员列表加载成功！');
    } catch (error) {
      console.error('加载人员列表失败:', error);
      message.error('加载人员列表失败: ' + (error.response?.data?.error || error.message));
    }
  }, []);

  // 加载系统指标
  const loadSystemMetrics = useCallback(async () => {
    try {
      const response = await axios.get(`${BACKEND_URL}/api/system_metrics`);
      setSystemStatus(response.data);
    } catch (error) {
      console.error('加载系统指标失败:', error);
      message.error('加载系统指标失败: ' + (error.response?.data?.error || error.message));
    }
  }, []);

  // 初始化数据和SocketIO连接
  useEffect(() => {
    loadSettings();
    loadHistory();
    loadStats();
    loadDevices();
    loadPersons();
    loadSystemMetrics();

    // 定时更新当前时间
    const timeInterval = setInterval(() => {
      setCurrentTime(moment());
    }, 1000);

    // 定时加载系统指标
    const systemMetricsInterval = setInterval(() => {
      loadSystemMetrics();
    }, 5000); // 每5秒更新一次系统指标

    // WebSocket连接
    const socket = io(BACKEND_URL, { transports: ['websocket'] });

    socket.on('connect', () => {
      message.success('已连接到实时日志服务！');
      setSystemLogs(prev => [`[${moment().format('HH:mm:ss')}] INFO - 已连接到服务器实时日志服务。`, ...prev.slice(0, 9)]);
    });

    socket.on('log_message', (data) => {
      setSystemLogs(prev => [`[${moment().format('HH:mm:ss')}] ${data.data}`, ...prev.slice(0, 9)]);
    });

    socket.on('new_alert', (alertData) => {
      message.warning(`新告警: ${alertData.title} @ ${alertData.location}`);
      setAlerts(prev => [alertData, ...prev]);
    });

    socket.on('training_status_update', (data) => {
      setModelTrainJobDetails(data.job);
      setModelTrainStatus(data.job.status);
      setModelTrainProgress(data.job.progress);
      if (data.job.status === 'completed') {
        message.success(`训练任务 ${data.job.id} 已完成！`);
        // 重新加载设置以获取新的模型版本
        loadSettings();
      } else if (data.job.status === 'failed') {
        message.error(`训练任务 ${data.job.id} 失败: ${data.job.error}`);
      } else if (data.job.status === 'cancelled') {
        message.info(`训练任务 ${data.job.id} 已取消。`);
      }
    });

    socket.on('training_queue_update', (data) => {
      setModelTrainQueue(data.queue);
    });

    socket.on('disconnect', () => {
      message.error('与实时日志服务断开连接。');
      setSystemLogs(prev => [`[${moment().format('HH:mm:ss')}] ERROR - 与服务器实时日志服务断开连接。`, ...prev.slice(0, 9)]);
    });

    socket.on('error', (err) => {
      console.error('Socket.IO Error:', err);
      message.error('实时日志服务连接错误。');
      setSystemLogs(prev => [`[${moment().format('HH:mm:ss')}] ERROR - 实时日志服务连接错误: ${err.message || err}.`, ...prev.slice(0, 9)]);
    });

    return () => {
      clearInterval(timeInterval);
      clearInterval(systemMetricsInterval);
      socket.disconnect();
    };
  }, [loadHistory, loadSettings, loadStats, loadDevices, loadPersons, loadSystemMetrics]);

  // AI聊天消息滚动到底部
  useEffect(() => {
    if (aiChatMessagesEndRef.current) {
      aiChatMessagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [aiChatMessages]);

  // 处理图片上传
  const handleImageUploadForAnalysis = (file) => {
    if (file.size > 5 * 1024 * 1024) {
      message.error('图片大小不能超过5MB');
      return Upload.LIST_IGNORE;
    }

    const reader = new FileReader();
    reader.onload = e => {
      setImageUrl(e.target.result);
      setOriginalImageForAnalysis(e.target.result);
      setResult(null);
      setAiInterpretation(null);
    };
    reader.readAsDataURL(file);
    return false;
  };

  // 清除上传的图片
  const clearUploadedImage = () => {
    setImageUrl(null);
    setOriginalImageForAnalysis(null);
    setResult(null);
    setAiInterpretation(null);
  };

  // 行为检测
  const handleDetect = async () => {
    if (!originalImageForAnalysis) {
      message.warning('请先上传图片');
      return;
    }

    setLoading(true);
    setResult(null);
    setAiInterpretation(null);

    try {
      const response = await axios.post(`${BACKEND_URL}/api/detect`, {
        imageBase64: originalImageForAnalysis,
        deviceId: 'manual_upload', // 标记为手动上传
        location: '未知区域' // 手动上传默认位置
      });

      const data = response.data;
      setResult({
        person_count: data.person_count,
        persons: data.persons.map(p => ({
          ...p,
          behavior: p.behavior || { label: '未知', value: 'unknown', color: 'gray' },
          safety_info: p.safety_info || { title: '未知', tips: ['未获取到安全信息'] }
        })),
        result_image_b64: data.result_image,
        safety_analysis: data.safety_analysis
      });
      message.success('行为监测完成！');

      if (systemSettings.ai_interpret_results) {
        setAiInterpretationLoading(true);
        const aiResponse = await axios.post(`${BACKEND_URL}/api/interpret_analysis`, {
          safety_analysis: data.safety_analysis
        });
        setAiInterpretation(aiResponse.data.interpretation);
        setAiInterpretationLoading(false);
      }

      loadHistory(); // 刷新历史记录
      loadStats(); // 刷新统计数据

    } catch (error) {
      console.error('行为监测失败:', error);
      const errorMessage = error.response?.data?.error || error.message;
      message.error('行为监测失败：' + errorMessage);
      if (error.response?.data?.result_image) {
        setImageUrl(error.response.data.result_image); // 显示错误图片
      }
      setResult({ error: { message: errorMessage } }); // 保存错误信息
    } finally {
      setLoading(false);
    }
  };

  // 紧急报警
  const handleEmergencySubmit = async (values) => {
    try {
      const response = await axios.post(`${BACKEND_URL}/api/campus/emergency`, values);
      message.success(response.data.message);
      setEmergencyModalVisible(false);
      emergencyForm.resetFields();
    } catch (error) {
      console.error('紧急报警失败:', error);
      message.error('紧急报警失败: ' + (error.response?.data?.error || error.message));
    }
  };

  // 签到
  const handleCheckinSubmit = async (values) => {
    try {
      const response = await axios.post(`${BACKEND_URL}/api/campus/checkin`, values);
      message.success(response.data.message);
      setCheckinModalVisible(false);
      checkinForm.resetFields();
      loadPersons(); // 刷新人员列表
      loadStats(); // 刷新统计数据
    } catch (error) {
      console.error('签到失败:', error);
      message.error('签到失败: ' + (error.response?.data?.error || error.message));
    }
  };

  // 添加设备
  const handleAddDeviceSubmit = async (values) => {
    try {
      const response = await axios.post(`${BACKEND_URL}/api/devices`, values);
      message.success(response.data.message);
      setAddDeviceModalVisible(false);
      addDeviceForm.resetFields();
      loadDevices(); // 刷新设备列表
      loadStats(); // 刷新统计数据
    } catch (error) {
      console.error('添加设备失败:', error);
      message.error('添加设备失败: ' + (error.response?.data?.error || error.message));
    }
  };

  // 处理摄像头选择
  const handleCameraSelect = async (camera) => {
    setSelectedCamera(camera);
    setCurrentStreamUrl(null); // 清除旧的流
    if (camera.status.value === 'online') {
      message.loading('正在加载视频流...', 0);
      try {
        const response = await axios.get(`${BACKEND_URL}/api/live-stream/${camera.id}`);
        setCurrentStreamUrl(response.data.stream_url);
        message.destroy();
        message.success('视频流加载成功！');
      } catch (error) {
        message.destroy();
        message.error('加载视频流失败: ' + (error.response?.data?.error || error.message));
        setCurrentStreamUrl(null);
      }
    } else {
      message.warning('该摄像头不在线或有故障，无法获取实时流。');
    }
  };

  // AI聊天消息处理
  const handleAiChatMessage = async (values) => {
    const userMessage = values.message;
    if (!userMessage.trim()) return;

    const newUserMessageEntry = {
      id: generateUniqueId(),
      role: 'user',
      content: userMessage,
      time: moment().format('HH:mm')
    };

    setAiChatMessages(prev => [...prev, newUserMessageEntry]);
    setAiChatLoading(true);
    aiChatForm.resetFields();

    try {
      const response = await axios.post(`${BACKEND_URL}/api/ai_chat`, {
        message: userMessage,
        conversation_id: ernieChatConversationId // 传递会话ID
      });

      setAiChatMessages(prev => [...prev, {
        id: generateUniqueId(),
        role: 'assistant',
        content: response.data.response,
        time: moment().format('HH:mm')
      }]);
    } catch (error) {
      console.error('AI助手聊天失败:', error);
      setAiChatMessages(prev => [...prev, {
        id: generateUniqueId(),
        role: 'assistant',
        content: 'AI助手暂时无法回应，请稍后再试。错误: ' + (error.response?.data?.error || error.message),
        time: moment().format('HH:mm')
      }]);
      message.error('AI助手聊天失败！');
    } finally {
      setAiChatLoading(false);
    }
  };

  // 图像理解处理
  const handleImageInterpret = async () => {
    if (!imageUploadFile) {
      message.warning('请先上传图片');
      return;
    }

    setImageInterpretLoading(true);
    setImageInterpretResult(null);

    try {
      const reader = new FileReader();
      reader.readAsDataURL(imageUploadFile);
      reader.onloadend = async () => {
        const imageBase64 = reader.result;
        const response = await axios.post(`${BACKEND_URL}/api/image_interpret`, {
          image_b64: imageBase64,
          text_prompt: imageQuestion
        });
        setImageInterpretResult(response.data.interpretation);
        message.success('图像理解完成！');
      };
    } catch (error) {
      console.error('图像理解失败:', error);
      message.error('图像理解失败：' + (error.response?.data?.error || error.message));
    } finally {
      setImageInterpretLoading(false);
    }
  };

  // 获取AI主动洞察
  const fetchAiProactiveInsight = useCallback(async () => {
    setAiProactiveInsightLoading(true);
    try {
      const response = await axios.post(`${BACKEND_URL}/api/ai_proactive_insights`, {
        current_stats: stats // 传递当前统计数据
      });
      setAiProactiveInsight(response.data.insight);
      message.success('AI主动洞察已更新！');
    } catch (error) {
      console.error('获取AI主动洞察失败:', error);
      setAiProactiveInsight('AI主动洞察获取失败: ' + (error.response?.data?.error || error.message));
      message.error('获取AI主动洞察失败！');
    } finally {
      setAiProactiveInsightLoading(false);
    }
  }, [stats]);

  // 获取AI告警处理建议
  const fetchAiAlertRecommendations = useCallback(async (alertData) => {
    setAiAlertRecommendationsLoading(true);
    try {
      const response = await axios.post(`${BACKEND_URL}/api/ai_recommend_alert_action`, alertData);
      setAiAlertRecommendations(response.data.recommendations);
      message.success('AI处理建议已生成！');
    } catch (error) {
      console.error('获取AI处理建议失败:', error);
      setAiAlertRecommendations('AI处理建议获取失败: ' + (error.response?.data?.error || error.message));
      message.error('获取AI处理建议失败！');
    } finally {
      setAiAlertRecommendationsLoading(false);
    }
  }, []);

  // 检查千帆API连接
  const checkQianfanAPI = async () => {
    setQianfanCheckLoading(true);
    try {
      const response = await axios.get(`${BACKEND_URL}/api/qianfan_check`);
      setQianfanCheckResult(response.data.message);
      message.success(response.data.message);
    } catch (error) {
      console.error('检查千帆API连接失败:', error);
      setQianfanCheckResult(error.response?.data?.message || '检查失败，请查看控制台日志。');
      message.error('检查千帆API连接失败！');
    } finally {
      setQianfanCheckLoading(false);
    }
  };

  // 提交模型训练任务
  const handleModelTrainSubmit = async (values) => {
    try {
      const response = await axios.post(`${BACKEND_URL}/api/train_model`, values);
      message.success(response.data.message);
      setModelTrainJobDetails(response.data.job); // 保存新创建的任务详情
      setModelTrainQueue(prev => [...prev, response.data.job_id]); // 添加到队列
      setModelTrainStatus('queued');
      setModelTrainProgress(0);
      modelTrainForm.resetFields();
    } catch (error) {
      console.error('提交模型训练任务失败:', error);
      message.error('提交模型训练任务失败: ' + (error.response?.data?.error || error.message));
      setModelTrainStatus('failed');
    }
  };

  // 取消模型训练任务
  const cancelModelTrainJob = async (jobId) => {
    try {
      const response = await axios.post(`${BACKEND_URL}/api/training/cancel/${jobId}`);
      message.info(response.data.message);
      // 后端会通过 socketio 发送状态更新，前端无需立即更改状态
    } catch (error) {
      console.error('取消模型训练任务失败:', error);
      message.error('取消模型训练任务失败: ' + (error.response?.data?.error || error.message));
    }
  };

  // 渲染人员详情卡片
  const renderPersonDetails = (person, index) => {
    const behaviorObj = person.behavior || { label: '未知', value: 'unknown', color: 'gray' };
    const isNormal = ['normal', 'stand', 'walk'].includes(behaviorObj.value);
    const severity = behaviorObj.value === 'danger' || behaviorObj.value === 'fall' ? 'error' :
      !isNormal ? 'warning' : 'success';
    const safetyInfo = person.safety_info || { title: isNormal ? '正常' : '异常', tips: [isNormal ? '行为正常' : '检测到异常'] };

    return (
      <Card
        key={person.id || index}
        hoverable
        className="details-card"
        onClick={() => setSelectedPerson(person)}
        style={{
          marginBottom: 16,
          borderRadius: token.borderRadius,
          border: `1px solid ${token.colorBorder}`
        }}
      >
        <Badge.Ribbon
          text={behaviorObj.label}
          color={severity === 'error' ? 'red' : severity === 'warning' ? 'orange' : 'green'}
        >
          <Row gutter={[16, 16]}>
            <Col xs={24} md={8}>
              <div className="image-preview-container-small">
                <Image
                  src={result?.result_image_b64 || imageUrl || '/placeholder-person.png'}
                  alt={`Detected person ${index + 1}`}
                  className="image-preview"
                  fallback="/placeholder-image.png"
                  style={{
                    borderRadius: token.borderRadius,
                    width: '100%',
                    height: 'auto'
                  }}
                />
              </div>
            </Col>
            <Col xs={24} md={16}>
              <div className="person-card-content">
                <Descriptions column={1} size="small" colon={false}>
                  <Descriptions.Item label="置信度">
                    <Progress
                      percent={parseFloat(person.confidence) * 100}
                      size="small"
                      status={parseFloat(person.confidence) > 0.8 ? 'success' : 'normal'}
                      format={p => `${p?.toFixed(0)}%`}
                      strokeColor={token.colorPrimary}
                    />
                  </Descriptions.Item>
                  <Descriptions.Item label="行为">
                    <Tag color={behaviorObj.color || token.colorPrimary}>{behaviorObj.label}</Tag>
                  </Descriptions.Item>
                </Descriptions>
                <Alert
                  message={<Text strong>{safetyInfo.title}</Text>}
                  description={
                    <ul style={{ paddingLeft: '20px', margin: 0, listStyleType: 'disc' }}>
                      {Array.isArray(safetyInfo.tips) ?
                        safetyInfo.tips.map((t, i) => <li key={i}>{t}</li>) :
                        <li>{String(safetyInfo.tips)}</li>
                      }
                    </ul>
                  }
                  type={severity}
                  showIcon
                  className="safety-alert-inner"
                />
              </div>
            </Col>
          </Row>
        </Badge.Ribbon>
      </Card>
    );
  };

  // 表格列定义
  const personColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80, responsive: ['lg'] },
    {
      title: '姓名/学号', dataIndex: 'name', key: 'name', render: (text, record) => (
        <Button type="link" onClick={() => setSelectedPerson(record)}>
          {text || record.studentId || '未知'}
        </Button>
      )
    },
    { title: '院系', dataIndex: 'department', key: 'department', responsive: ['lg'] },
    {
      title: '行为', dataIndex: 'behavior', key: 'behavior', render: (behavior) => (
        <Tag color={behavior?.color || token.colorPrimary}>{behavior?.label || '未知'}</Tag>
      )
    },
    { title: '位置', dataIndex: 'location', key: 'location' },
    { title: '时间', dataIndex: 'time', key: 'time', sorter: (a, b) => moment(a.time).unix() - moment(b.time).unix(), responsive: ['md'] },
    {
      title: '置信度', dataIndex: 'confidence', key: 'confidence', render: (text) => (
        <Progress
          percent={parseFloat(text) * 100}
          size="small"
          status={parseFloat(text) > 0.8 ? 'success' : 'normal'}
          format={p => `${p?.toFixed(0)}%`}
          strokeColor={token.colorPrimary}
        />
      ), responsive: ['lg']
    }
  ];

  const deviceColumns = [
    {
      title: '设备名称', dataIndex: 'name', key: 'name', render: (text, record) => (
        <Button type="link" onClick={() => setSelectedDevice(record)}>{text}</Button>
      )
    },
    { title: 'IP地址', dataIndex: 'ip', key: 'ip', responsive: ['lg'] },
    { title: '位置', dataIndex: 'location', key: 'location' },
    {
      title: '类型', dataIndex: 'device_type', key: 'device_type', responsive: ['md'], render: (text) => (
        <Tag color={token.colorPrimary}>{deviceTypes.find(d => d.value === text)?.label || text}</Tag>
      )
    },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: (status) => (
        <Tag color={status?.color || token.colorTextSecondary}>{status?.label || '未知'}</Tag>
      )
    },
    { title: '最后活跃', dataIndex: 'lastActive', key: 'lastActive', sorter: (a, b) => moment(a.lastActive).unix() - moment(b.lastActive).unix(), responsive: ['lg'] },
    {
      title: '操作', key: 'action', render: (_, record) => (
        <Space size="small">
          <Tooltip title="实时监控">
            <Button
              type="text"
              icon={<VideoCameraOutlined />}
              onClick={() => {
                handleCameraSelect(record);
                setLiveModalVisible(true);
              }}
              disabled={record.status.value !== 'online'}
            />
          </Tooltip>
          <Tooltip title="编辑(开发中)">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => message.info('编辑功能开发中!')}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  const alertColumns = [
    {
      title: '告警标题', dataIndex: 'title', key: 'title', render: (text, record) => (
        <Button
          type="link"
          onClick={() => {
            setSelectedAlert(record);
            setAlertDrawerVisible(true);
            fetchAiAlertRecommendations(record); // 打开告警详情时获取AI建议
          }}
        >
          {text}
        </Button>
      )
    },
    {
      title: '级别', dataIndex: 'level', key: 'level', responsive: ['md'], render: (level) => (
        <Tag color={level?.color || token.colorTextSecondary}>{level?.label || '未知'}</Tag>
      )
    },
    { title: '位置', dataIndex: 'location', key: 'location' },
    { title: '时间', dataIndex: 'time', key: 'time', sorter: (a, b) => moment(a.time).unix() - moment(b.time).unix(), responsive: ['lg'] },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: (status) => {
        let color = 'default';
        if (status === '未处理') color = 'red';
        if (status === '处理中') color = 'orange';
        if (status === '已解决') color = 'green';
        return <Tag color={color}>{status}</Tag>;
      }
    }
  ];

  // Ant Design 的 ConfigProvider 主题配置
  const currentThemeConfig = {
    algorithm: darkModeActive ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
    token: {
      colorPrimary: `var(--theme-primary-color)`,
      colorInfo: `var(--theme-primary-color)`,
      colorSuccess: `var(--theme-success-color)`,
      colorWarning: `var(--theme-warning-color)`,
      colorError: `var(--theme-error-color)`,
      colorTextBase: `var(--theme-text-primary)`,
      colorBgContainer: `var(--theme-card-bg)`, // Card, Modal, Drawer body, default background
      colorBorder: `var(--theme-border-color)`,
      colorBgLayout: `var(--theme-background)`, // Layout background
      colorText: `var(--theme-text-primary)`,
      colorTextSecondary: `var(--theme-text-secondary)`,
      colorTextTertiary: `var(--theme-text-tertiary)`,
      borderRadius: 8, // 全局圆角
    },
    components: {
      Layout: {
        headerBg: `var(--theme-header-bg)`,
        siderBg: `var(--theme-sider-bg)`,
        footerBg: `var(--theme-footer-bg)`
      },
      Card: {
        headerBg: `var(--theme-card-header-bg)`,
        colorTextHeading: `var(--theme-text-title)`,
        colorText: `var(--theme-text-primary)`
      },
      Table: {
        headerBg: `var(--theme-table-header-bg)`,
        headerColor: `var(--theme-text-title)`,
        colorText: `var(--theme-text-primary)`,
        rowHoverBg: `var(--theme-menu-hover-bg)`
      },
      Menu: {
        itemBg: 'transparent',
        itemSelectedBg: `var(--theme-menu-selected-bg)`,
        itemHoverBg: `var(--theme-menu-hover-bg)`,
        itemColor: `var(--theme-menu-text)`,
        itemSelectedColor: `var(--theme-menu-selected-text)`,
        itemHoverColor: `var(--theme-menu-hover-text)`,
        subMenuItemBg: 'transparent',
      },
      Input: {
        activeBorderColor: `var(--theme-primary-color)`,
        hoverBorderColor: `var(--theme-primary-color)`,
        // activeShadow: `0 0 0 3px rgba(var(--theme-primary-color-rgb), 0.15)`, // 避免重复定义，使用CSS变量
        addonBg: `var(--theme-input-bg)`,
        colorText: `var(--theme-text-input)`,
        colorBgContainer: `var(--theme-input-bg)`,
        colorBorder: `var(--theme-input-border-color)`
      },
      Select: {
        optionActiveBg: `var(--theme-menu-hover-bg)`,
        optionSelectedBg: `var(--theme-menu-selected-bg)`,
        optionSelectedColor: `var(--theme-menu-selected-text)`,
        colorText: `var(--theme-text-input)`,
        colorBgContainer: `var(--theme-input-bg)`,
        colorBorder: `var(--theme-input-border-color)`
      },
      Button: {
        colorPrimary: `var(--theme-primary-color)`,
        colorPrimaryHover: `color-mix(in srgb, var(--theme-primary-color) 90%, black)`,
        colorPrimaryActive: `color-mix(in srgb, var(--theme-primary-color) 80%, black)`,
        colorLink: `var(--theme-primary-color)`,
        colorLinkHover: `color-mix(in srgb, var(--theme-primary-color) 80%, black)`,
        colorText: `var(--theme-text-primary)`,
        colorBgContainer: `var(--theme-card-bg)`,
        colorBorder: `var(--theme-border-color)`,
      },
      Modal: {
        headerBg: `var(--theme-modal-header-bg)`,
        colorTextHeading: `var(--theme-text-title)`,
        colorBgContainer: `var(--theme-card-bg)`
      },
      Drawer: {
        headerBg: `var(--theme-drawer-header-bg)`,
        colorTextHeading: `var(--theme-text-title)`,
        colorBgLayout: `var(--theme-card-bg)`
      },
      Dropdown: {
        colorBgElevated: `var(--theme-card-bg)`,
        colorText: `var(--theme-text-primary)`,
        controlItemBgHover: `var(--theme-menu-hover-bg)`,
      },
      Breadcrumb: {
        itemColor: `var(--theme-text-secondary)`,
        lastItemColor: `var(--theme-text-primary)`
      },
      Spin: {
        contentBg: `var(--theme-content-bg)`
      }
    }
  };

  return (
    <ConfigProvider theme={currentThemeConfig}>
      {/* 移除 Watermark 组件 */}
      <Layout className="app-layout" style={{ minHeight: '100vh', background: `var(--theme-background)` }}>
        <Header className="app-header" style={{
          background: `var(--theme-header-bg)`,
          padding: '0 24px',
          boxShadow: `var(--theme-box-shadow)`,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          height: 64,
          zIndex: 100
        }}>
          <div className="logo-container" style={{ display: 'flex', alignItems: 'center' }}>
            <SafetyOutlined className="logo-icon" style={{ fontSize: 28, color: `var(--theme-primary-color)`, marginRight: 12 }} />
            <span className="logo-text" style={{
              fontSize: 18,
              fontWeight: 'bold',
              color: `var(--theme-text-title)`
            }}>智守平安助手</span>
          </div>

          <Space className="header-actions" size="middle">
            <Tooltip title={systemSettings.theme === 'dark' ? '切换亮色模式' : '切换暗色模式'}>
              <Button
                icon={systemSettings.theme === 'dark' ? <BulbOutlined /> : <PoweroffOutlined />}
                shape="circle"
                onClick={() => {
                  const newTheme = systemSettings.theme === 'dark' ? 'light' : 'dark';
                  const newActiveTheme = newTheme === 'dark' ? 'default' : 'standard-light'; // 亮色默认standard-light，暗色默认default
                  handleSaveSettings({ ...systemSettings, theme: newTheme, active_theme: newActiveTheme });
                }}
              />
            </Tooltip>

            <Dropdown
              menu={{
                items: notifications.map(n => ({
                  key: n.id,
                  label: (
                    <div className="notification-item" style={{ padding: '8px 0', minWidth: 300 }}>
                      <Avatar
                        icon={n.type === 'warning' ? <WarningOutlined /> : n.type === 'success' ? <CheckCircleOutlined /> : <BellOutlined />}
                        style={{
                          backgroundColor: n.type === 'warning' ? `var(--theme-warning-color)` : `var(--theme-primary-color)`,
                          marginRight: 8
                        }}
                      />
                      <div className="notification-content">
                        <div className="notification-title" style={{ fontWeight: 'bold' }}>{n.title}</div>
                        <div className="notification-time" style={{ color: `var(--theme-text-secondary)` }}>{n.time}</div>
                      </div>
                    </div>
                  )
                }))
              }}
              placement="bottomRight"
              trigger={['click']}
            >
              <Badge count={notifications.filter(n => !n.read).length} size="small">
                <Button icon={<BellOutlined />} shape="circle" />
              </Badge>
            </Dropdown>

            <Button icon={<CustomerServiceOutlined />} onClick={() => setActiveTab('9')}>AI助手</Button>
            <Button icon={<CheckCircleOutlined />} onClick={() => setCheckinModalVisible(true)}>签到</Button>
            <Button icon={<FundProjectionScreenOutlined />} onClick={() => {
              setLiveModalVisible(true);
              const onlineCamera = devices.find(d => d.status.value === 'online') || (devices.length > 0 ? devices[0] : null);
              if (onlineCamera) setSelectedCamera(onlineCamera);
              if (onlineCamera) handleCameraSelect(onlineCamera); // 自动加载第一个在线摄像头流
            }}>实时监控</Button>
            <Button type="primary" danger icon={<WarningOutlined />} onClick={() => setEmergencyModalVisible(true)}>紧急报警</Button>
          </Space>
        </Header>

        <Layout style={{ marginTop: 64 }}>
          <Sider
            width={220}
            collapsedWidth={80}
            collapsed={collapsed}
            collapsible
            trigger={null}
            className="app-sider"
            style={{
              background: `var(--theme-sider-bg)`,
              borderRight: `1px solid var(--theme-border-color)`,
              position: 'fixed',
              height: 'calc(100vh - 64px)',
              left: 0,
              zIndex: 90
            }}
          >
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              className="sider-collapse-button"
              style={{
                position: 'absolute',
                top: 12,
                right: -40,
                zIndex: 1,
                background: `var(--theme-sider-bg)`,
                border: `1px solid var(--theme-border-color)`,
                boxShadow: `var(--theme-box-shadow)`
              }}
            />
            <Menu
              mode="inline"
              selectedKeys={[activeTab]}
              onClick={e => setActiveTab(e.key)}
              className="app-menu"
              style={{ borderRight: 0, paddingTop: 12 }}
              items={[
                { key: '1', icon: <DashboardOutlined />, label: '行为监测' },
                { key: '2', icon: <HistoryOutlined />, label: '历史记录' },
                { key: '3', icon: <BarChartOutlined />, label: '数据统计' },
                { key: '9', icon: <CustomerServiceOutlined />, label: '智守AI助手' },
                { key: '10', icon: <CodeSandboxOutlined />, label: '多模态图像理解' },
                { key: '4', icon: <TeamOutlined />, label: '人员管理' },
                { key: '5', icon: <VideoCameraOutlined />, label: '设备管理' },
                { key: '8', icon: <ExperimentOutlined />, label: '大模型训练' },
                { key: '6', icon: <AlertOutlined />, label: '告警中心' },
                { key: '7', icon: <SettingOutlined />, label: '系统设置' }
              ]}
            />
          </Sider>

          <Content
            className="app-content"
            style={{
              marginLeft: collapsed ? 80 : 220,
              padding: 24,
              transition: 'margin-left 0.2s',
              minHeight: 'calc(100vh - 64px)'
            }}
          >
            <Breadcrumb style={{ marginBottom: 24 }} items={[
              { title: '首页' },
              {
                title: {
                  '1': '行为监测', '2': '历史记录', '3': '数据统计',
                  '4': '人员管理', '5': '设备管理', '6': '告警中心',
                  '7': '系统设置', '8': '大模型训练', '9': '智守AI助手',
                  '10': '多模态图像理解'
                }[activeTab] || '首页'
              }
            ]} />

            {activeTab === '1' && (
              <div className="tab-section behavior-monitoring-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>行为监测分析</Title>
                <Row gutter={[24, 24]}>
                  <Col xs={24} md={10} lg={8}>
                    <Card
                      title="图像上传与控制"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Dragger
                        name="file"
                        multiple={false}
                        beforeUpload={handleImageUploadForAnalysis}
                        onRemove={clearUploadedImage}
                        showUploadList={!!imageUrl}
                        accept="image/*"
                        height={220}
                        className="image-dragger"
                        style={{ borderRadius: token.borderRadius }}
                      >
                        {imageUrl ? (
                          <Image
                            src={imageUrl}
                            preview={false}
                            style={{
                              maxHeight: '100%',
                              objectFit: 'contain',
                              borderRadius: token.borderRadius
                            }}
                          />
                        ) : (
                          <div style={{ padding: 16, textAlign: 'center' }}>
                            <p className="ant-upload-drag-icon" style={{ fontSize: 48, color: `var(--theme-primary-color)` }}>
                              <PictureOutlined />
                            </p>
                            <p className="ant-upload-text" style={{ fontWeight: 'bold', color: `var(--theme-text-primary)` }}>
                              点击或拖拽图片到此区域上传
                            </p>
                            <p className="ant-upload-hint" style={{ color: `var(--theme-text-secondary)` }}>
                              支持PNG, JPG等格式. 最大5MB.
                            </p>
                          </div>
                        )}
                      </Dragger>
                      <Space direction="vertical" style={{ width: '100%', marginTop: '16px' }}>
                        <Button
                          type="primary"
                          icon={<SendOutlined />}
                          onClick={handleDetect}
                          loading={loading}
                          disabled={!originalImageForAnalysis || loading}
                          block
                          size="large"
                        >
                          {loading ? '分析中...' : '开始分析'}
                        </Button>
                        {originalImageForAnalysis &&
                          <Button
                            icon={<ClearOutlined />}
                            onClick={clearUploadedImage}
                            block
                            disabled={loading}
                            size="large"
                          >
                            清除图片
                          </Button>
                        }
                      </Space>
                    </Card>
                  </Col>

                  <Col xs={24} md={14} lg={16}>
                    {loading && (
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'center',
                          alignItems: 'center',
                          height: 400,
                          background: `var(--theme-card-bg)`,
                          borderRadius: token.borderRadius,
                          border: `1px dashed var(--theme-border-color)`,
                          marginBottom: 24
                        }}
                      >
                        <Spin size="large" tip="图像分析中，请稍候..." />
                      </div>
                    )}

                    {!loading && result && (
                      <Card
                        title="分析结果"
                        className="result-card"
                        bordered={false}
                        style={{ background: `var(--theme-card-bg)` }}
                      >
                        <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
                          <Col xs={24} sm={8}>
                            <Statistic
                              title="检测人数"
                              value={result.person_count || 0}
                              prefix={<TeamOutlined style={{ color: `var(--theme-primary-color)` }} />}
                              valueStyle={{ color: `var(--theme-primary-color)` }}
                            />
                          </Col>
                          <Col xs={24} sm={8}>
                            <Statistic
                              title="正常行为"
                              value={(result.persons || []).filter(p => ['normal', 'stand', 'walk'].includes(p?.behavior?.value)).length}
                              prefix={<CheckCircleOutlined style={{ color: `var(--theme-success-color)` }} />}
                              valueStyle={{ color: `var(--theme-success-color)` }}
                            />
                          </Col>
                          <Col xs={24} sm={8}>
                            <Statistic
                              title="异常行为"
                              value={(result.persons || []).filter(p => !['normal', 'stand', 'walk'].includes(p?.behavior?.value)).length}
                              prefix={<WarningOutlined style={{ color: `var(--theme-warning-color)` }} />}
                              valueStyle={{ color: `var(--theme-warning-color)` }}
                            />
                          </Col>
                        </Row>

                        <Tabs defaultActiveKey="1" className="result-tabs">
                          <TabPane tab="人员详情" key="1">
                            {(result.persons || []).length > 0 ?
                              (result.persons || []).map((p, idx) => renderPersonDetails(p, idx)) :
                              <Empty
                                description="未检测到人员"
                                imageStyle={{ height: 80 }}
                                style={{ padding: 40 }}
                              />
                            }
                          </TabPane>

                          <TabPane tab="整体评估与AI解读" key="2">
                            <Alert
                              message={result.error?.message ? "分析出错" :
                                (result.persons || []).some(p => !['normal', 'stand', 'walk'].includes(p?.behavior?.value)) ?
                                  "检测到潜在风险" : "场景安全"
                              }
                              description={result.error?.message || result.safety_analysis || "无安全分析结果"}
                              type={result.error?.message ? "error" :
                                (result.persons || []).some(p => !['normal', 'stand', 'walk'].includes(p?.behavior?.value)) ?
                                  "warning" : "success"
                              }
                              showIcon
                              style={{ marginBottom: 24, whiteSpace: 'pre-wrap' }}
                            />
                            <Title level={5} style={{ marginTop: 24 }}>
                              <TrademarkCircleOutlined style={{ marginRight: 8 }} />
                              AI助手解读 (AppBuilder)
                            </Title>
                            {aiInterpretationLoading ? (
                              <Spin tip="AI解读中..." />
                            ) : aiInterpretation ? (
                              <Alert
                                message="AI助手解读"
                                description={
                                  <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
                                    {aiInterpretation}
                                  </Paragraph>
                                }
                                type="info"
                                showIcon
                              />
                            ) : (
                              <Empty
                                description={systemSettings.ai_interpret_results ? "暂无解读或解读失败" : "AI解读功能已关闭"}
                                imageStyle={{ height: 80 }}
                                style={{ padding: 20 }}
                              />
                            )}
                          </TabPane>
                        </Tabs>
                      </Card>
                    )}

                    {!loading && !result && (
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'center',
                          alignItems: 'center',
                          height: 400,
                          background: `var(--theme-card-bg)`,
                          borderRadius: token.borderRadius,
                          border: `1px dashed var(--theme-border-color)`
                        }}
                      >
                        <Empty
                          description="请先上传图片并开始分析"
                          imageStyle={{ height: 80 }}
                        />
                      </div>
                    )}
                  </Col>
                </Row>
              </div>
            )}

            {activeTab === '2' && (
              <div className="tab-section history-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>历史记录</Title>
                <Timeline mode="alternate" className="history-timeline">
                  {history.length > 0 ? history.map((item) => (
                    <Timeline.Item
                      key={item.id}
                      dot={<ClockCircleOutlined style={{ fontSize: '16px', color: `var(--theme-primary-color)` }} />}
                    >
                      <Card
                        className="details-card timeline-card"
                        style={{ background: `var(--theme-card-bg)` }}
                      >
                        <Row gutter={16}>
                          <Col xs={24} sm={8}>
                            <div className="image-preview-container-small">
                              <Image
                                src={item.result_image_b64 || item.original_image_b64}
                                alt="检测结果"
                                className="image-preview"
                                fallback="/placeholder-image.png"
                                style={{ borderRadius: token.borderRadius }}
                              />
                            </div>
                          </Col>
                          <Col xs={24} sm={16}>
                            <Descriptions column={1} size="small" className="timeline-info">
                              <Descriptions.Item label="时间">{item.timestamp}</Descriptions.Item>
                              <Descriptions.Item label="位置">{item.location || '未知'}</Descriptions.Item>
                              <Descriptions.Item label="人数">{item.person_count || 0}</Descriptions.Item>
                            </Descriptions>
                            {item.error ?
                              <Alert
                                message="识别失败"
                                description={`错误: ${item.error.message}`}
                                type="error"
                                showIcon
                                className="safety-alert-inner"
                              /> :
                              <>
                                <Paragraph
                                  ellipsis={{ rows: 2, expandable: true, symbol: '更多' }}
                                  className="report-text-small"
                                  style={{ whiteSpace: 'pre-wrap' }}
                                >
                                  <strong>分析:</strong> {item.safety_analysis || '无'}
                                </Paragraph>
                                <Button
                                  type="primary"
                                  size="small"
                                  onClick={() => {
                                    setActiveTab('1');
                                    setImageUrl(item.result_image_b64 || item.original_image_b64);
                                    setOriginalImageForAnalysis(item.original_image_b64);
                                    setResult(item);
                                  }}
                                >
                                  查看详情
                                </Button>
                              </>
                            }
                          </Col>
                        </Row>
                      </Card>
                    </Timeline.Item>
                  )) : <Empty description="暂无历史记录" />}
                </Timeline>
              </div>
            )}

            {activeTab === '3' && (
              <div className="tab-section stats-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>数据统计与分析</Title>
                <div style={{ marginBottom: 16, textAlign: 'right' }}>
                  <Segmented
                    options={[
                      { label: '卡片视图', value: 'cards', icon: <AppstoreAddOutlined /> },
                      { label: '图表视图', value: 'charts', icon: <RadarChartOutlined /> }
                    ]}
                    value={dashboardView}
                    onChange={setDashboardView}
                  />
                </div>

                {dashboardView === 'cards' ? (
                  <>
                    <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
                      <Col xs={24} sm={12} md={6}>
                        <Card
                          className="stat-highlight-card"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Statistic
                            title="总检测人数"
                            value={stats.totalDetections}
                            prefix={<TeamOutlined style={{ color: `var(--theme-primary-color)` }} />}
                            valueStyle={{ color: `var(--theme-primary-color)` }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card
                          className="stat-highlight-card success"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Statistic
                            title="安全行为占比"
                            value={stats.totalDetections > 0 ? (stats.safePersons / stats.totalDetections * 100).toFixed(1) : 0}
                            suffix="%"
                            prefix={<SafetyCertificateOutlined style={{ color: `var(--theme-success-color)` }} />}
                            valueStyle={{ color: `var(--theme-success-color)` }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card
                          className="stat-highlight-card warning"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Statistic
                            title="警报次数"
                            value={stats.alerts}
                            prefix={<AlertOutlined style={{ color: `var(--theme-warning-color)` }} />}
                            valueStyle={{ color: `var(--theme-warning-color)` }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card
                          className="stat-highlight-card info"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Statistic
                            title="设备在线率"
                            value={stats.devices > 0 ? (stats.onlineDevices / stats.devices * 100).toFixed(1) : 0}
                            suffix="%"
                            prefix={<VideoCameraOutlined style={{ color: `var(--theme-primary-color)` }} />}
                            valueStyle={{ color: `var(--theme-primary-color)` }}
                          />
                        </Card>
                      </Col>
                    </Row>

                    <Row gutter={[16, 16]}>
                      <Col xs={24} lg={12}>
                        <Card
                          title="行为类型统计"
                          className="chart-card"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="PieChart"
                            data={[['行为类型', '数量'], ...stats.behaviorStats]}
                            options={{
                              pieHole: 0.4,
                              backgroundColor: 'transparent',
                              titleTextStyle: { color: token.colorText },
                              legend: { textStyle: { color: token.colorTextSecondary } },
                              colors: [`var(--theme-success-color)`, `var(--theme-error-color)`, `var(--theme-warning-color)`, '#f5222d', '#fa8c16', '#722ed1', `var(--theme-primary-color)`, '#13c2c2', '#eb2f96', '#bfbfbf']
                            }}
                            width="100%"
                            height="350px"
                          />
                        </Card>
                      </Col>

                      <Col xs={24} lg={12}>
                        <Card
                          title="位置活跃度统计"
                          className="chart-card"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="BarChart"
                            data={[['位置', '人数'], ...stats.locationStats]}
                            options={{
                              chartArea: { width: '65%' },
                              backgroundColor: 'transparent',
                              titleTextStyle: { color: token.colorText },
                              hAxis: {
                                title: '人数',
                                minValue: 0,
                                textStyle: { color: token.colorTextSecondary },
                                titleTextStyle: { color: token.colorTextSecondary }
                              },
                              vAxis: {
                                title: '位置',
                                textStyle: { color: token.colorTextSecondary },
                                titleTextStyle: { color: token.colorTextSecondary }
                              },
                              colors: [`var(--theme-primary-color)`],
                              legend: { textStyle: { color: token.colorTextSecondary } }
                            }}
                            width="100%"
                            height="350px"
                          />
                        </Card>
                      </Col>
                    </Row>

                    <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                      <Col xs={24}>
                        <Card
                          title="行为时间分布趋势 (正常 vs 异常)"
                          className="chart-card"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="LineChart"
                            data={[['时间', '正常行为', '异常行为'], ...stats.timeTrend]}
                            options={{
                              curveType: 'function',
                              backgroundColor: 'transparent',
                              titleTextStyle: { color: token.colorText },
                              legend: { position: 'bottom', textStyle: { color: token.colorTextSecondary } },
                              hAxis: { textStyle: { color: token.colorTextSecondary } },
                              vAxis: { textStyle: { color: token.colorTextSecondary } },
                              series: { 0: { color: `var(--theme-success-color)` }, 1: { color: `var(--theme-error-color)` } }
                            }}
                            width="100%"
                            height="350px"
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                ) : (
                  <Card
                    className="chart-card"
                    bordered={false}
                    style={{ background: `var(--theme-card-bg)` }}
                  >
                    <Row gutter={[24, 24]}>
                      <Col xs={24} md={12}>
                        <Card
                          title="行为类型分布"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="PieChart"
                            data={[['行为类型', '数量'], ...stats.behaviorStats]}
                            options={{
                              title: '行为类型分布',
                              pieHole: 0.4,
                              backgroundColor: 'transparent',
                              legend: { position: 'right', textStyle: { color: token.colorTextSecondary } },
                              titleTextStyle: { color: token.colorText },
                              colors: [`var(--theme-success-color)`, `var(--theme-error-color)`, `var(--theme-warning-color)`, '#f5222d', '#fa8c16', '#722ed1', `var(--theme-primary-color)`, '#13c2c2', '#eb2f96', '#bfbfbf']
                            }}
                            width="100%"
                            height="300px"
                          />
                        </Card>
                      </Col>

                      <Col xs={24} md={12}>
                        <Card
                          title="位置活跃度"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="BarChart"
                            data={[['位置', '人数'], ...stats.locationStats]}
                            options={{
                              title: '位置活跃度',
                              chartArea: { width: '70%' },
                              hAxis: { title: '人数', minValue: 0, textStyle: { color: token.colorTextSecondary } },
                              vAxis: { title: '位置', textStyle: { color: token.colorTextSecondary } },
                              backgroundColor: 'transparent',
                              legend: { position: 'none' },
                              titleTextStyle: { color: token.colorText },
                              colors: [`var(--theme-primary-color)`]
                            }}
                            width="100%"
                            height="300px"
                          />
                        </Card>
                      </Col>

                      <Col xs={24}>
                        <Card
                          title="行为时间趋势"
                          bordered={false}
                          style={{ background: `var(--theme-card-bg)` }}
                        >
                          <Chart
                            chartType="LineChart"
                            data={[['时间', '正常行为', '异常行为'], ...stats.timeTrend]}
                            options={{
                              title: '行为时间趋势',
                              curveType: 'function',
                              legend: { position: 'bottom', textStyle: { color: token.colorTextSecondary } },
                              backgroundColor: 'transparent',
                              hAxis: { textStyle: { color: token.colorTextSecondary } },
                              vAxis: { textStyle: { color: token.colorTextSecondary } },
                              titleTextStyle: { color: token.colorText },
                              series: { 0: { color: `var(--theme-success-color)` }, 1: { color: `var(--theme-error-color)` } }
                            }}
                            width="100%"
                            height="300px"
                          />
                        </Card>
                      </Col>
                    </Row>
                  </Card>
                )}
              </div>
            )}

            {activeTab === '4' && (
              <div className="tab-section">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>人员管理</Title>
                <Card
                  title="人员行为记录"
                  className="table-card"
                  bordered={false}
                  style={{ background: `var(--theme-card-bg)` }}
                  extra={
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={() => setCheckinModalVisible(true)}
                    >
                      新增签到/人员
                    </Button>
                  }
                >
                  <Table
                    columns={personColumns}
                    dataSource={persons}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                    scroll={{ x: 'max-content' }}
                  />
                </Card>
              </div>
            )}

            {activeTab === '5' && (
              <div className="tab-section">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>设备管理</Title>
                <Card
                  title="监控设备列表"
                  className="table-card"
                  bordered={false}
                  style={{ background: `var(--theme-card-bg)` }}
                  extra={
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={loadDevices}>刷新</Button>
                      <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddDeviceModalVisible(true)}>
                        添加设备
                      </Button>
                    </Space>
                  }
                >
                  <Table
                    columns={deviceColumns}
                    dataSource={devices}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                    scroll={{ x: 'max-content' }}
                  />
                </Card>
                <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
                  <Col xs={24} lg={12}>
                    <Card
                      title="设备状态分布"
                      className="chart-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Chart
                        chartType="PieChart"
                        data={[
                          ['状态', '数量'],
                          ['在线', devices.filter(d => d.status.value === 'online').length],
                          ['离线', devices.filter(d => d.status.value === 'offline').length],
                          ['故障', devices.filter(d => d.status.value === 'error').length],
                          ['维护中', devices.filter(d => d.status.value === 'maintenance').length]
                        ]}
                        options={{
                          pieHole: 0.4,
                          backgroundColor: 'transparent',
                          titleTextStyle: { color: token.colorText },
                          legend: { textStyle: { color: token.colorTextSecondary } },
                          colors: [`var(--theme-success-color)`, `var(--theme-text-secondary)`, `var(--theme-error-color)`, `var(--theme-warning-color)`]
                        }}
                        width="100%"
                        height="300px"
                      />
                    </Card>
                  </Col>
                  <Col xs={24} lg={12}>
                    <Card
                      title="设备位置分布"
                      className="chart-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Chart
                        chartType="BarChart"
                        data={[
                          ['位置', '设备数量'],
                          ...campusLocations.map(loc => [
                            loc,
                            devices.filter(d => d.location === loc).length
                          ])
                        ]}
                        options={{
                          chartArea: { width: '70%' },
                          backgroundColor: 'transparent',
                          titleTextStyle: { color: token.colorText },
                          hAxis: {
                            title: '数量',
                            minValue: 0,
                            textStyle: { color: token.colorTextSecondary },
                            titleTextStyle: { color: token.colorTextSecondary }
                          },
                          vAxis: {
                            title: '位置',
                            textStyle: { color: token.colorTextSecondary },
                            titleTextStyle: { color: token.colorTextSecondary }
                          },
                          colors: [`var(--theme-primary-color)`],
                          legend: { textStyle: { color: token.colorTextSecondary } }
                        }}
                        width="100%"
                        height="300px"
                      />
                    </Card>
                  </Col>
                </Row>
              </div>
            )}

            {activeTab === '6' && (
              <div className="tab-section">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>告警中心</Title>
                <Card
                  title="告警记录"
                  className="table-card"
                  bordered={false}
                  style={{ background: `var(--theme-card-bg)` }}
                  extra={
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={() => loadStats()}>刷新</Button> {/* 刷新告警数据 */}
                      <Button icon={<FilterOutlined />}>筛选</Button>
                    </Space>
                  }
                >
                  <Table
                    columns={alertColumns}
                    dataSource={alerts}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                    scroll={{ x: 'max-content' }}
                  />
                </Card>
                <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
                  <Col xs={24} lg={12}>
                    <Card
                      title="告警级别分布"
                      className="chart-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Chart
                        chartType="PieChart"
                        data={[
                          ['级别', '数量'],
                          ['低', alerts.filter(a => a.level.value === 'low').length],
                          ['中', alerts.filter(a => a.level.value === 'medium').length],
                          ['高', alerts.filter(a => a.level.value === 'high').length],
                          ['紧急', alerts.filter(a => a.level.value === 'critical').length]
                        ]}
                        options={{
                          pieHole: 0.4,
                          backgroundColor: 'transparent',
                          titleTextStyle: { color: token.colorText },
                          legend: { textStyle: { color: token.colorTextSecondary } },
                          colors: [`var(--theme-primary-color)`, `var(--theme-warning-color)`, `var(--theme-error-color)`, '#722ed1']
                        }}
                        width="100%"
                        height="300px"
                      />
                    </Card>
                  </Col>
                  <Col xs={24} lg={12}>
                    <Card
                      title="告警趋势 (24小时)"
                      className="chart-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Chart
                        chartType="LineChart"
                        data={[
                          ['时间', '告警数量'],
                          ...Array.from({ length: 24 }, (_, i) => {
                            const h = i;
                            const c = Math.floor(Math.random() * 10);
                            return [`${h.toString().padStart(2, '0')}:00`, c];
                          })
                        ]}
                        options={{
                          curveType: 'function',
                          backgroundColor: 'transparent',
                          titleTextStyle: { color: token.colorText },
                          legend: { position: 'bottom', textStyle: { color: token.colorTextSecondary } },
                          hAxis: { textStyle: { color: token.colorTextSecondary } },
                          vAxis: { textStyle: { color: token.colorTextSecondary } },
                          series: { 0: { color: `var(--theme-error-color)` } }
                        }}
                        width="100%"
                        height="300px"
                      />
                    </Card>
                  </Col>
                </Row>
              </div>
            )}

            {activeTab === '9' && (
              <div className="tab-section ai-assistant-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>智守AI助手 (ERNIE-Speed)</Title>
                <Row gutter={[24, 24]}>
                  <Col xs={24} lg={12}>
                    <Card
                      title={<><RobotOutlined /> ERNIE AI聊天机器人</>}
                      className="ai-feature-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <div
                        className="chat-window"
                        style={{
                          height: 400,
                          overflowY: 'auto',
                          padding: 16,
                          background: `var(--theme-card-bg)`,
                          borderRadius: token.borderRadius,
                          marginBottom: 16,
                          border: `1px solid var(--theme-border-color)`
                        }}
                      >
                        <List
                          itemLayout="vertical"
                          dataSource={aiChatMessages}
                          renderItem={msg => (
                            <List.Item
                              key={msg.id}
                              className={`chat-message ${msg.role}`}
                              style={{
                                padding: '12px 0',
                                borderBottom: `1px solid var(--theme-border-color)`
                              }}
                            >
                              <List.Item.Meta
                                avatar={
                                  <Avatar
                                    icon={msg.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                                    style={{
                                      background: msg.role === 'assistant' ? `var(--theme-primary-color)` : `var(--theme-input-bg)`
                                    }}
                                  />
                                }
                                title={
                                  <Space>
                                    <Text strong className="message-role" style={{ color: msg.role === 'assistant' ? `var(--theme-primary-color)` : `var(--theme-text-primary)` }}>
                                      {msg.role === 'user' ? '您' : '智守助手'}
                                    </Text>
                                    <Text type="secondary" style={{ fontSize: '0.8em', color: `var(--theme-text-secondary)` }}>
                                      {msg.time}
                                    </Text>
                                  </Space>
                                }
                                description={
                                  <div
                                    className="message-content-bubble"
                                    style={{
                                      padding: 12,
                                      borderRadius: token.borderRadius,
                                      background: msg.role === 'assistant' ? `var(--theme-menu-hover-bg)` : `var(--theme-primary-color)`,
                                      color: msg.role === 'assistant' ? `var(--theme-text-primary)` : `var(--theme-button-primary-text)`,
                                      marginTop: 8
                                    }}
                                  >
                                    <Paragraph style={{ marginBottom: 0, whiteSpace: 'pre-wrap' }}>
                                      {msg.content}
                                    </Paragraph>
                                  </div>
                                }
                              />
                            </List.Item>
                          )}
                        />
                        <div ref={aiChatMessagesEndRef} />
                      </div>

                      <Form form={aiChatForm} onFinish={handleAiChatMessage} className="chat-input-form">
                        <Input.Group compact style={{ display: 'flex' }}>
                          <Form.Item name="message" noStyle rules={[{ required: true, message: '请输入消息!' }]}>
                            <Input
                              placeholder="向ERNIE助手提问..."
                              onPressEnter={() => aiChatForm.submit()}
                              style={{ flexGrow: 1 }}
                              size="large"
                            />
                          </Form.Item>
                          <Button
                            type="primary"
                            htmlType="submit"
                            loading={aiChatLoading}
                            icon={<SendOutlined />}
                            size="large"
                          />
                        </Input.Group>
                      </Form>
                    </Card>
                  </Col>

                  <Col xs={24} lg={12}>
                    <Card
                      title={<><ThunderboltOutlined /> 主动风险预警 (AppBuilder)</>}
                      className="ai-feature-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                      extra={
                        <Tooltip title="AI基于统计数据生成预警">
                          <Button
                            icon={<ReloadOutlined />}
                            onClick={fetchAiProactiveInsight}
                            loading={aiProactiveInsightLoading}
                          >
                            刷新
                          </Button>
                        </Tooltip>
                      }
                    >
                      {aiProactiveInsightLoading ? (
                        <Spin tip="AI生成预警中..." />
                      ) : aiProactiveInsight ? (
                        <Alert
                          message="AI安全概览报告"
                          description={
                            <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
                              {aiProactiveInsight}
                            </Paragraph>
                          }
                          type="info"
                          showIcon
                        />
                      ) : (
                        <Empty
                          description="点击刷新获取AI预警"
                          imageStyle={{ height: 80 }}
                          style={{ padding: 40 }}
                        />
                      )}
                    </Card>

                    <Card
                      title={<><SolutionOutlined /> AI智能决策建议 (AppBuilder)</>}
                      className="ai-feature-card"
                      bordered={false}
                      style={{
                        background: `var(--theme-card-bg)`,
                        marginTop: 24
                      }}
                    >
                      <Empty
                        description="（此功能集成在告警详情中）"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        imageStyle={{ height: 80 }}
                        style={{ padding: 20 }}
                      />

                      <Divider />

                      <Title level={5} style={{ marginBottom: 16 }}>AI安全学习资料</Title>
                      <List
                        itemLayout="horizontal"
                        dataSource={[
                          { title: '校园安全应急响应指南', url: '#' },
                          { title: '行为识别技术在安防的应用', url: '#' },
                          { title: '智能监控系统操作手册', url: '#' }
                        ]}
                        renderItem={item => (
                          <List.Item
                            actions={[
                              <Button
                                type="link"
                                icon={<ReadOutlined />}
                                onClick={() => message.info('跳转: ' + item.url)}
                              >
                                阅读
                              </Button>
                            ]}
                            style={{ padding: '12px 0' }}
                          >
                            <List.Item.Meta
                              avatar={<BookOutlined style={{ fontSize: 20, color: `var(--theme-primary-color)` }} />}
                              title={
                                <a href={item.url} target="_blank" rel="noopener noreferrer" style={{ color: `var(--theme-text-primary)` }}>
                                  {item.title}
                                </a>
                              }
                            />
                          </List.Item>
                        )}
                      />
                    </Card>
                  </Col>
                </Row>
              </div>
            )}

            {activeTab === '10' && (
              <div className="tab-section multimodal-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>多模态图像理解 (百度智能云)</Title>
                <Card
                  title="上传图片并提问"
                  className="control-card"
                  bordered={false}
                  style={{ background: `var(--theme-card-bg)` }}
                >
                  <Form layout="vertical">
                    <Form.Item label="选择图片">
                      <Dragger
                        beforeUpload={(file) => {
                          setImageUploadFile(file);
                          const reader = new FileReader();
                          reader.onload = e => setImageUrl(e.target.result);
                          reader.readAsDataURL(file);
                          return false;
                        }}
                        onRemove={() => {
                          setImageUploadFile(null);
                          setImageUrl(null);
                        }}
                        maxCount={1}
                        accept="image/*"
                        height={200}
                        className="image-dragger"
                        style={{ borderRadius: token.borderRadius }}
                      >
                        {imageUrl ? (
                          <Image
                            src={imageUrl}
                            preview={false}
                            style={{
                              maxHeight: '180px',
                              objectFit: 'contain',
                              borderRadius: token.borderRadius
                            }}
                          />
                        ) : (
                          <div style={{ padding: 16, textAlign: 'center' }}>
                            <p className="ant-upload-drag-icon" style={{ fontSize: 48, color: `var(--theme-primary-color)` }}>
                              <PictureOutlined />
                            </p>
                            <p className="ant-upload-text" style={{ fontWeight: 'bold', color: `var(--theme-text-primary)` }}>上传用于AI理解的图片</p>
                          </div>
                        )}
                      </Dragger>
                    </Form.Item>
                    <Form.Item label="您的问题">
                      <TextArea
                        rows={3}
                        value={imageQuestion}
                        onChange={(e) => setImageQuestion(e.target.value)}
                        placeholder="例如：'图片里有什么？' 或 '描述图中的主要物体及其位置关系。'"
                        style={{ background: `var(--theme-input-bg)`, color: `var(--theme-text-input)` }}
                      />
                    </Form.Item>
                    <Form.Item>
                      <Button
                        type="primary"
                        onClick={handleImageInterpret}
                        loading={imageInterpretLoading}
                        icon={<SendOutlined />}
                        disabled={!imageUploadFile || imageInterpretLoading}
                      >
                        {imageInterpretLoading ? '分析中...' : '开始图像理解'}
                      </Button>
                    </Form.Item>
                  </Form>
                  <Divider />
                  <Title level={5}>AI理解结果</Title>
                  {imageInterpretLoading ? (
                    <Spin tip="AI图像理解中..." />
                  ) : imageInterpretResult ? (
                    <Alert
                      message="AI的回答"
                      description={
                        <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
                          {imageInterpretResult}
                        </Paragraph>
                      }
                      type="success"
                      showIcon
                    />
                  ) : (
                    <Empty
                      description="AI理解结果将显示在此"
                      imageStyle={{ height: 80 }}
                      style={{ padding: 20 }}
                    />
                  )}
                </Card>
              </div>
            )}

            {activeTab === '8' && (
              <div className="tab-section model-train-tab">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>大模型训练 (模拟)</Title>
                <Row gutter={[24, 24]}>
                  <Col xs={24} lg={12}>
                    <Card
                      title="提交新训练任务"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Form
                        layout="vertical"
                        form={modelTrainForm}
                        onFinish={handleModelTrainSubmit}
                        initialValues={{
                          model_type: 'yolov8',
                          dataset_name: '校园行为数据集-v1',
                          epochs: 100,
                          batch_size: 16,
                          imgsz: 640
                        }}
                      >
                        <Form.Item label="模型类型" name="model_type" rules={[{ required: true }]}>
                          <Select>
                            <Option value="yolov8">YOLOv8</Option>
                            <Option value="yolov9">YOLOv9 (即将推出)</Option>
                          </Select>
                        </Form.Item>
                        <Form.Item label="训练数据集" name="dataset_name" rules={[{ required: true }]}>
                          <Input placeholder="例如：校园行为数据集-v1" />
                        </Form.Item>
                        <Form.Item label="训练轮次 (Epochs)" name="epochs" rules={[{ required: true }]}>
                          <InputNumber min={1} max={500} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item label="批大小 (Batch Size)" name="batch_size" rules={[{ required: true }]}>
                          <InputNumber min={1} max={64} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item label="图片尺寸 (imgsz)" name="imgsz" rules={[{ required: true }]}>
                          <InputNumber min={320} max={1280} step={32} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item>
                          <Button type="primary" htmlType="submit" block loading={modelTrainStatus === 'training'}>
                            提交训练任务
                          </Button>
                        </Form.Item>
                      </Form>
                    </Card>
                  </Col>
                  <Col xs={24} lg={12}>
                    <Card
                      title="当前训练任务状态"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      {modelTrainJobDetails ? (
                        <>
                          <Descriptions column={1} size="small" bordered style={{ marginBottom: 16 }}>
                            <Descriptions.Item label="任务ID">{modelTrainJobDetails.id}</Descriptions.Item>
                            <Descriptions.Item label="模型类型">{modelTrainJobDetails.model_type}</Descriptions.Item>
                            <Descriptions.Item label="数据集">{modelTrainJobDetails.dataset_name}</Descriptions.Item>
                            <Descriptions.Item label="状态">
                              <Tag color={
                                modelTrainStatus === 'training' ? 'blue' :
                                  modelTrainStatus === 'completed' ? 'green' :
                                    modelTrainStatus === 'failed' ? 'red' :
                                      modelTrainStatus === 'queued' ? 'gold' : 'default'
                              }>
                                {modelTrainStatus === 'training' ? '训练中' :
                                  modelTrainStatus === 'completed' ? '已完成' :
                                    modelTrainStatus === 'failed' ? '失败' :
                                      modelTrainStatus === 'queued' ? '排队中' : '等待'}
                              </Tag>
                            </Descriptions.Item>
                            <Descriptions.Item label="进度">
                              <Progress
                                percent={modelTrainProgress}
                                status={modelTrainStatus === 'failed' ? 'exception' : modelTrainStatus === 'completed' ? 'success' : 'active'}
                              />
                            </Descriptions.Item>
                            {modelTrainStatus === 'training' && (
                              <Descriptions.Item label="当前轮次">{modelTrainJobDetails.current_epoch}/{modelTrainJobDetails.epochs}</Descriptions.Item>
                            )}
                            {modelTrainJobDetails.estimated_remaining && modelTrainStatus === 'training' && (
                              <Descriptions.Item label="预计剩余时间">
                                {modelTrainJobDetails.estimated_remaining}
                              </Descriptions.Item>
                            )}
                            {modelTrainStatus === 'failed' && (
                              <Descriptions.Item label="错误信息">
                                <Alert type="error" message={modelTrainJobDetails.error} showIcon />
                              </Descriptions.Item>
                            )}
                            {modelTrainStatus === 'completed' && modelTrainJobDetails.new_model_version && (
                              <Descriptions.Item label="新模型版本">
                                <Tag color="green">{modelTrainJobDetails.new_model_version}</Tag>
                                <Alert type="success" message={`新模型 ${modelTrainJobDetails.new_model_version} 已生成并应用。`} showIcon style={{ marginTop: 8 }} />
                              </Descriptions.Item>
                            )}
                          </Descriptions>
                          {modelTrainStatus !== 'completed' && modelTrainStatus !== 'failed' && (
                            <Button
                              danger
                              onClick={() => cancelModelTrainJob(modelTrainJobDetails.id)}
                              disabled={modelTrainStatus === 'cancelled'}
                              block
                            >
                              取消任务
                            </Button>
                          )}
                        </>
                      ) : (
                        <Empty description="暂无训练任务" imageStyle={{ height: 80 }} />
                      )}
                    </Card>
                    <Card
                      title="训练任务队列"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)`, marginTop: 24 }}
                    >
                      {modelTrainQueue.length > 0 ? (
                        <List
                          size="small"
                          bordered
                          dataSource={modelTrainQueue}
                          renderItem={(jobId, idx) => {
                            const job = modelTrainJobDetails && modelTrainJobDetails.id === jobId ? modelTrainJobDetails : { status: 'queued', model_type: '未知', dataset_name: '未知' }; // If not current, default
                            return (
                              <List.Item>
                                <List.Item.Meta
                                  avatar={<Avatar>{idx + 1}</Avatar>}
                                  title={`任务ID: ${jobId}`}
                                  description={`状态: ${job.status === 'training' ? '训练中' : job.status === 'queued' ? '排队中' : job.status}, 模型: ${job.model_type}, 数据集: ${job.dataset_name}`}
                                />
                                {job.status === 'queued' && (
                                  <Button size="small" danger onClick={() => cancelModelTrainJob(jobId)}>取消</Button>
                                )}
                              </List.Item>
                            );
                          }}
                        />
                      ) : (
                        <Empty description="训练队列为空" imageStyle={{ height: 80 }} />
                      )}
                    </Card>
                  </Col>
                </Row>
              </div>
            )}

            {activeTab === '7' && (
              <div className="tab-section">
                <Title level={3} className="section-title" style={{ marginBottom: 24 }}>系统设置</Title>
                <Row gutter={[24, 24]}>
                  <Col xs={24} lg={12}>
                    <Card
                      title="系统配置"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Form
                        layout="vertical"
                        form={settingsForm}
                        initialValues={systemSettings}
                        onFinish={handleSaveSettings}
                      >
                        <Row gutter={[16, 16]}>
                          <Col xs={24} sm={12}>
                            <Form.Item label="检测灵敏度" name="sensitivity">
                              <Select>
                                <Option value="low">低</Option>
                                <Option value="medium">中</Option>
                                <Option value="high">高</Option>
                              </Select>
                            </Form.Item>
                          </Col>
                          <Col xs={24} sm={12}>
                            <Form.Item label="报警通知" name="notification">
                              <Select>
                                <Option value="all">所有</Option>
                                <Option value="important">重要</Option>
                                <Option value="none">关闭</Option>
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                        <Form.Item label="Ant Design 主题 (明暗模式)" name="theme">
                          <Radio.Group>
                            <Radio.Button value="light">亮色</Radio.Button>
                            <Radio.Button value="dark">暗色</Radio.Button>
                            {/* <Radio.Button value="auto">自动</Radio.Button> */}
                          </Radio.Group>
                        </Form.Item>
                        <Form.Item label="自定义皮肤 (仅部分主题生效)" name="active_theme">
                          <Radio.Group>
                            <Radio.Button value="standard-light">标准亮白</Radio.Button>
                            <Radio.Button value="default">科技深蓝</Radio.Button>
                            <Radio.Button value="ice">冰雪世界</Radio.Button>
                            <Radio.Button value="fire">火焰领土</Radio.Button>
                          </Radio.Group>
                        </Form.Item>

                        <Collapse accordion className="settings-collapse">
                          <Panel header="AI模型与功能 (AppBuilder & YOLO)" key="1">
                            <Form.Item label="行为识别模型" name="model_version">
                              <Select>
                                <Option value="yolov8n-pose">YOLOv8n-pose</Option>
                                <Option value="yolov8s-pose">YOLOv8s-pose</Option>
                                <Option value="yolov8x-pose">YOLOv8x-pose</Option> {/* 增加更多选项 */}
                              </Select>
                            </Form.Item>
                            <Form.Item label="检测置信度阈值" name="confidence_threshold">
                              <Slider min={0} max={100} step={1} marks={{ 0: '0%', 50: '50%', 100: '100%' }} />
                            </Form.Item>
                            <Form.Item label="AppBuilder应用ID (非聊天AI)" name="app_builder_app_id">
                              <Input placeholder="用于安全报告、预警等" />
                            </Form.Item>
                            <Form.Item label="AI解读监测结果 (AppBuilder)" name="ai_interpret_results" valuePropName="checked">
                              <Switch />
                            </Form.Item>
                            <Form.Item label="AI主动风险预警 (AppBuilder)" name="ai_proactive_alerts" valuePropName="checked">
                              <Switch />
                            </Form.Item>
                          </Panel>
                          <Panel header="通知设置" key="2">
                            <Form.Item label="通知方式" name="notification_methods">
                              <Checkbox.Group options={[
                                { label: '系统通知', value: 'system' },
                                { label: '邮件', value: 'email' },
                                { label: '短信', value: 'sms' }
                              ]} />
                            </Form.Item>
                            <Form.Item label="声音提醒" name="sound_reminders" valuePropName="checked">
                              <Switch />
                            </Form.Item>
                          </Panel>
                        </Collapse>
                        <Form.Item style={{ marginTop: 24 }}>
                          <Space>
                            <Button type="primary" htmlType="submit" loading={loading}>保存设置</Button>
                            <Button onClick={() => settingsForm.resetFields()}>恢复默认</Button>
                          </Space>
                        </Form.Item>
                      </Form>
                    </Card>
                  </Col>
                  <Col xs={24} lg={12}>
                    <Card
                      title="系统信息与状态"
                      className="control-card"
                      bordered={false}
                      style={{ background: `var(--theme-card-bg)` }}
                    >
                      <Descriptions column={{ xs: 1, sm: 2 }} bordered size="small">
                        <Descriptions.Item label="系统版本" span={2}>v5.2.0-ERNIE</Descriptions.Item>
                        <Descriptions.Item label="模型版本" span={2}>{systemSettings.model_version}</Descriptions.Item>
                        <Descriptions.Item label="AppBuilder SDK (非聊天)" span={2}>
                          <Tag color={systemStatus.appbuilder_client_initialized ? "green" : "red"}>
                            {systemStatus.appbuilder_client_initialized ? "已连接" : "未连接"}
                          </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="千帆Token (聊天/图像)" span={2}>
                          <Tag color={systemStatus.qianfan_token_available ? "green" : "red"}>
                            {systemStatus.qianfan_token_available ? "有效" : "无效/过期"}
                          </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="CPU">
                          <Progress percent={Math.round(systemStatus.cpu)} status={systemStatus.cpu > 80 ? 'exception' : 'normal'} size="small" />
                        </Descriptions.Item>
                        <Descriptions.Item label="内存">
                          <Progress percent={Math.round(systemStatus.memory)} status={systemStatus.memory > 80 ? 'exception' : 'normal'} size="small" />
                        </Descriptions.Item>
                      </Descriptions>
                      <Button
                        onClick={checkQianfanAPI}
                        loading={qianfanCheckLoading}
                        icon={<InfoCircleOutlined />}
                        style={{ marginTop: 16 }}
                        block
                      >
                        检查 ERNIE-Speed API 连接
                      </Button>
                      {qianfanCheckResult && (
                        <Alert
                          message="ERNIE API检查结果"
                          description={qianfanCheckResult}
                          type={qianfanCheckResult.includes('正常') ? 'success' : 'error'}
                          showIcon
                          style={{ marginTop: 16 }}
                        />
                      )}
                    </Card>
                    <Card
                      title="系统日志 (最新)"
                      className="control-card"
                      bordered={false}
                      style={{
                        background: `var(--theme-card-bg)`,
                        marginTop: 24
                      }}
                    >
                      <div className="system-logs-container" style={{ height: 200, overflowY: 'auto' }}>
                        {systemLogs.length > 0 ? systemLogs.map((log, idx) => (
                          <div key={idx} className="log-entry" style={{ padding: '8px 0', borderBottom: `1px solid var(--theme-border-color)` }}>
                            <Text type="secondary" style={{ fontSize: '0.8em', marginRight: '8px' }}>{log.substring(0, 19)}</Text> {/* Extract timestamp */}
                            <Text style={{ color: log.includes('ERROR') ? token.colorError : log.includes('WARNING') ? token.colorWarning : token.colorText }}>{log.substring(log.indexOf(' - ') + 3)}</Text> {/* Extract message */}
                          </div>
                        )) : <Empty description="暂无日志" imageStyle={{ height: 60 }} />}
                      </div>
                    </Card>
                  </Col>
                </Row>
              </div>
            )}
          </Content>
        </Layout>

        <Footer className="app-footer" style={{
          textAlign: 'center',
          background: `var(--theme-footer-bg)`,
          borderTop: `1px solid var(--theme-border-color)`,
          padding: '16px 50px'
        }}>
          <div style={{ marginBottom: 8 }}>智守平安助手 ©2025</div>
          <div style={{ fontSize: '0.8em', color: `var(--theme-text-secondary)` }}>
            当前时间: {currentTime.format('YYYY-MM-DD HH:mm:ss')}
          </div>
        </Footer>

        {/* 模态框和抽屉 */}
        <Modal
          title="紧急报警"
          open={emergencyModalVisible}
          onCancel={() => setEmergencyModalVisible(false)}
          footer={null}
          width={600}
          centered
        >
          <Form form={emergencyForm} layout="vertical" onFinish={handleEmergencySubmit}>
            <Form.Item
              name="location"
              label="报警位置"
              rules={[{ required: true, message: '请选择报警位置' }]}
            >
              <Select placeholder="选择位置">
                {campusLocations.map(l => (
                  <Option key={l} value={l}>{l}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="description" label="情况描述">
              <TextArea rows={4} placeholder="简述情况" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" danger block size="large">
                确认报警
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="校园签到"
          open={checkinModalVisible}
          onCancel={() => setCheckinModalVisible(false)}
          footer={null}
          width={600}
          centered
        >
          <Form form={checkinForm} layout="vertical" onFinish={handleCheckinSubmit}>
            <Form.Item
              name="student_id"
              label="学号"
              rules={[{ required: true, message: '请输入学号' }]}
            >
              <Input placeholder="输入学号" />
            </Form.Item>
            <Form.Item
              name="location"
              label="签到位置"
              rules={[{ required: true, message: '请选择签到位置' }]}
            >
              <Select placeholder="选择位置">
                {campusLocations.map(l => (
                  <Option key={l} value={l}>{l}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block size="large">
                确认签到
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={`实时监控 - ${selectedCamera?.name || '选择摄像头'}`}
          open={liveModalVisible}
          onCancel={() => {
            setLiveModalVisible(false);
            setCurrentStreamUrl(null);
          }}
          footer={null}
          width="80vw"
          style={{ maxWidth: '1000px' }}
          bodyStyle={{ padding: 0, height: '60vh', display: 'flex' }}
          centered
          className="live-stream-modal"
        >
          <div
            className="camera-list-sider-modal"
            style={{
              width: 200,
              borderRight: `1px solid var(--theme-border-color)`,
              overflowY: 'auto'
            }}
          >
            <Menu
              mode="inline"
              selectedKeys={selectedCamera ? [selectedCamera.id] : []}
              onSelect={({ key }) => {
                const cam = devices.find(d => d.id === key);
                if (cam) handleCameraSelect(cam);
              }}
              items={devices.map(d => ({
                key: d.id,
                icon: <VideoCameraOutlined />,
                label: d.name,
                disabled: d.status.value !== 'online'
              }))}
              className="camera-menu-modal"
              style={{ background: 'transparent' }}
            />
          </div>
          <div
            className="video-content-area-modal"
            style={{
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              padding: 16
            }}
          >
            {selectedCamera ? (
              <>
                <div
                  className="video-player-container-modal"
                  style={{
                    flex: 1,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    background: `var(--theme-card-bg)`,
                    borderRadius: token.borderRadius,
                    marginBottom: 16,
                    minHeight: '200px' // Make sure it has a min height
                  }}
                >
                  {currentStreamUrl && selectedCamera.status.value === 'online' ? (
                    <video
                      ref={videoRef}
                      src={currentStreamUrl}
                      controls
                      autoPlay
                      muted
                      loop
                      style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', borderRadius: token.borderRadius }}
                    />
                  ) : selectedCamera.status.value === 'online' ? (
                    <Spin size="large" tip="加载视频流中..." />
                  ) : (
                    <Result
                      status="warning"
                      title="设备离线"
                      subTitle={`${selectedCamera.name}当前状态: ${selectedCamera.status.label}。`}
                    />
                  )}
                </div>
                <Descriptions
                  column={1}
                  size="small"
                  bordered
                  className="device-stream-info-modal"
                  style={{ background: `var(--theme-card-bg)` }}
                >
                  <Descriptions.Item label="名称">{selectedCamera.name}</Descriptions.Item>
                  <Descriptions.Item label="IP">{selectedCamera.ip}</Descriptions.Item>
                  <Descriptions.Item label="位置">{selectedCamera.location}</Descriptions.Item>
                  <Descriptions.Item label="状态">
                    <Tag color={selectedCamera.status.color}>{selectedCamera.status.label}</Tag>
                  </Descriptions.Item>
                </Descriptions>
              </>
            ) : (
              <div
                className="empty-selection-modal"
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: '100%'
                }}
              >
                <Empty description="请选择摄像头" />
              </div>
            )}
          </div>
        </Modal>

        <Modal
          title="添加新设备"
          open={addDeviceModalVisible}
          onCancel={() => setAddDeviceModalVisible(false)}
          footer={null}
          width={600}
          centered
        >
          <Form form={addDeviceForm} layout="vertical" onFinish={handleAddDeviceSubmit}>
            <Form.Item
              name="name"
              label="设备名称"
              rules={[{ required: true, message: '请输入设备名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="ip"
              label="IP地址"
              rules={[
                { required: true, message: '请输入IP地址' },
                { pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: 'IP地址格式无效' }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="location"
              label="位置"
              rules={[{ required: true, message: '请选择位置' }]}
            >
              <Select>
                {campusLocations.map(l => (
                  <Option key={l} value={l}>{l}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="device_type"
              label="类型"
              rules={[{ required: true, message: '请选择设备类型' }]}
              initialValue="camera"
            >
              <Select>
                {deviceTypes.map(t => (
                  <Option key={t.value} value={t.value}>{t.label}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择设备状态' }]}
              initialValue="online"
            >
              <Select>
                {deviceStatusTypes.map(s => (
                  <Option key={s.value} value={s.value}>{s.label}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block size="large">
                添加
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <Drawer
          title="告警详情"
          placement="right"
          width={Math.min(600, window.innerWidth * 0.9)}
          onClose={() => {
            setSelectedAlert(null);
            setAlertDrawerVisible(false);
            setAiAlertRecommendations(null); // 清除AI建议
          }}
          open={alertDrawerVisible}
        >
          {selectedAlert ? (
            <>
              <Descriptions column={1} bordered size="small">
                <Descriptions.Item label="标题">{selectedAlert.title}</Descriptions.Item>
                <Descriptions.Item label="级别">
                  <Tag color={selectedAlert.level.color}>{selectedAlert.level.label}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="位置">{selectedAlert.location}</Descriptions.Item>
                <Descriptions.Item label="时间">{selectedAlert.time}</Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={
                    selectedAlert.status === '未处理' ? 'red' :
                      selectedAlert.status === '处理中' ? 'orange' : 'green'
                  }>
                    {selectedAlert.status}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="描述">{selectedAlert.description}</Descriptions.Item>
              </Descriptions>
              <Divider />
              <Title level={5}><CrownOutlined /> AI处理建议 (AppBuilder)</Title>
              <Button
                onClick={() => fetchAiAlertRecommendations(selectedAlert)}
                loading={aiAlertRecommendationsLoading}
                icon={<BulbOutlined />}
                style={{ marginBottom: 16 }}
              >
                获取AI建议
              </Button>
              {aiAlertRecommendationsLoading ? (
                <Spin tip="AI建议生成中..." />
              ) : aiAlertRecommendations ? (
                <Alert
                  message="AI处理建议"
                  description={
                    <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
                      {aiAlertRecommendations}
                    </Paragraph>
                  }
                  type="info"
                  showIcon
                />
              ) : (
                <Empty description="点击获取建议" />
              )}
              <Divider />
              <Title level={5}>处理记录(示例)</Title>
              <Timeline
                items={[
                  { children: '告警触发' },
                  { children: '通知安保' },
                  { children: '现场核实' },
                  { children: '问题解决' }
                ]}
              />
              <Divider />
              <Title level={5}>处理告警</Title>
              <Form layout="vertical">
                <Form.Item label="状态">
                  <Select defaultValue="pending">
                    <Option value="pending">未处理</Option>
                    <Option value="processing">处理中</Option>
                    <Option value="resolved">已解决</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="意见">
                  <TextArea rows={3} />
                </Form.Item>
                <Form.Item>
                  <Button type="primary">提交</Button>
                </Form.Item>
              </Form>
            </>
          ) : <Empty description="未选择告警" />}
        </Drawer>

        <Drawer
          title="人员详情"
          placement="right"
          width={Math.min(600, window.innerWidth * 0.9)}
          onClose={() => setSelectedPerson(null)}
          open={!!selectedPerson}
        >
          {selectedPerson ? (
            <>
              <div style={{ textAlign: 'center', marginBottom: 24 }}>
                <Avatar
                  size={100}
                  icon={<UserOutlined />}
                  style={{
                    background: `var(--theme-primary-color)`,
                    marginBottom: 16
                  }}
                />
                <Title level={4} style={{ marginTop: 16 }}>{selectedPerson.name || `ID: ${selectedPerson.studentId}`}</Title>
              </div>
              <Descriptions column={1} bordered size="small">
                <Descriptions.Item label="学号">{selectedPerson.studentId || 'N/A'}</Descriptions.Item>
                <Descriptions.Item label="院系">{selectedPerson.department || 'N/A'}</Descriptions.Item>
                <Descriptions.Item label="行为">
                  <Tag color={selectedPerson.behavior?.color || token.colorPrimary}>
                    {selectedPerson.behavior?.label || '未知'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="位置">{selectedPerson.location || 'N/A'}</Descriptions.Item>
                <Descriptions.Item label="时间">{selectedPerson.time || 'N/A'}</Descriptions.Item>
                <Descriptions.Item label="置信度">
                  <Progress percent={parseFloat(selectedPerson.confidence) * 100} size="small" />
                </Descriptions.Item>
              </Descriptions>
              <Divider />
              <Title level={5}>近期活动</Title>
              <Table
                columns={[
                  { title: '时间', dataIndex: 'time' },
                  { title: '行为', dataIndex: 'behavior', render: (b) => <Tag color={b?.color || token.colorPrimary}>{b?.label || '未知'}</Tag> },
                  { title: '位置', dataIndex: 'location' }
                ]}
                dataSource={selectedPerson.activityHistory || []}
                pagination={false}
                size="small"
              />
              <Divider />
              <Title level={5}>操作</Title>
              <Space wrap>
                <Button type="primary">查看档案</Button>
                <Button>发送通知</Button>
                <Button danger>标记可疑</Button>
              </Space>
            </>
          ) : <Empty description="未选择人员" />}
        </Drawer>

        <Drawer
          title="设备详情"
          placement="right"
          width={Math.min(600, window.innerWidth * 0.9)}
          onClose={() => setSelectedDevice(null)}
          open={!!selectedDevice}
        >
          {selectedDevice ? (
            <>
              <div style={{ textAlign: 'center', marginBottom: 24 }}>
                <Avatar
                  icon={<VideoCameraOutlined />}
                  size={100}
                  style={{
                    background: selectedDevice.status.color === 'green' ? `var(--theme-success-color)` : `var(--theme-text-secondary)`,
                    marginBottom: 16
                  }}
                />
                <Title level={4} style={{ marginTop: 16 }}>{selectedDevice.name}</Title>
                <Tag color={selectedDevice.status.color}>{selectedDevice.status.label}</Tag>
              </div>
              <Descriptions column={1} bordered size="small">
                <Descriptions.Item label="IP">{selectedDevice.ip}</Descriptions.Item>
                <Descriptions.Item label="位置">{selectedDevice.location}</Descriptions.Item>
                <Descriptions.Item label="类型">
                  {deviceTypes.find(d => d.value === selectedDevice.device_type)?.label || selectedDevice.device_type}
                </Descriptions.Item>
                <Descriptions.Item label="最后活跃">{selectedDevice.lastActive}</Descriptions.Item>
              </Descriptions>
              <Divider />
              <Title level={5}>操作</Title>
              <Space wrap>
                <Button
                  type="primary"
                  onClick={() => {
                    handleCameraSelect(selectedDevice);
                    setLiveModalVisible(true);
                    setSelectedDevice(null);
                  }}
                  disabled={selectedDevice.status.value !== 'online'}
                >
                  实时监控
                </Button>
                <Button>配置</Button>
                {selectedDevice.status.value === 'offline' && (
                  <Button type="primary" danger>重启</Button>
                )}
                <Button>维护记录</Button>
              </Space>
            </>
          ) : <Empty description="未选择设备" />}
        </Drawer>

        <BackTop />
        <FloatButton.BackTop visibilityHeight={300} />
      </Layout>
    </ConfigProvider>
  );
}

export default App;
